package {
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	[SWF(width=550,height=400)]
	public class VoronoiDiagram extends Sprite
	{
		public var count:int = 0;
		public var points:Array = [];
		
		public function VoronoiDiagram()
		{
			stage.addEventListener(MouseEvent.CLICK, onClick);
		}
		
		public function onClick(e:MouseEvent):void
		{
			points[count] = new Point(this.mouseX, this.mouseY);
			
			count++;
			
			var i:int=0;
			var j:int=0;
			
			var p1:Point;
			var p2:Point;
			var p3:Point;
			var m:Number;
			var b:Number;
			
			var g:Graphics = this.graphics;
			g.clear();
			g.lineStyle(1,0);
			g.beginFill(0,1);
			for(i; i<count; i++)
			{
				p1 = points[i];
				g.drawCircle(p1.x,p1.y,2);
				for(j=i+1; j<count; j++){
					p2 = points[j];
					p3 = Point.interpolate(p1,p2,.5);
					m = (p1.y-p2.y)/(p1.x-p2.x);
					m = -1/m;
					if(m != Number.POSITIVE_INFINITY && m != Number.NEGATIVE_INFINITY)
					{
						b = (p3.y - m*p3.x);
						g.moveTo(0,b);
						g.lineTo(stage.stageWidth, m*stage.stageWidth + b);
					}
					else
					{
						g.moveTo(p3.x,0);
						g.lineTo(p3.x,stage.stageHeight);
					}
				}
			}
			
		}
	}
}
